<template>
  <div>
    <span v-if="props.showText">{{currName}}</span>
    <el-switch
      v-if="options.length > 1"
      v-model="modelValue"
      class="cc-switch"
      inline-prompt
      :active-text="options[0].value"
      :active-value="options[0].key"
      :inactive-text="options[1].value"
      :inactive-value="options[1].key"
      @change="handleChange"
    ></el-switch>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { getDictionary } from '@/utils/system';

const emit = defineEmits(['change']);
const props = defineProps({
  dictCode: String,
  showText: Boolean
})

const modelValue = defineModel();
const currName = ref('');
const options = ref([]);

const handleChange = () => {
  emit('change');
};

const loadDicAndShow = async(dictCode) => {
  if ((dictCode || '') === '') {
    options.value = [];
  } else {
    options.value = await getDictionary(dictCode);
  }

  calcValue();
};

const calcValue = () => {
  currName.value = '';
  if (props.showText) {
    options.value.forEach(option => {
      if (option.key === modelValue.value) {
        currName.value = option.value;
      }
    });
  }
};

watch(() => props.dictCode, (dictCode) => {
  loadDicAndShow(dictCode);
}, {immediate: true});

watch(() => modelValue.value, () => {
  calcValue();
});
</script>